﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace DotNetExtensions.AspNet.Encryptions
{
    public class MD5
    {
        public static string Hash(string data)
        {
            if (string.IsNullOrEmpty(data)) return null;

            byte[] byts = Encoding.UTF8.GetBytes(data);

            return Hash(byts, 0, byts.Length);
        }
        public static string Hash(byte[] byts, int offset, int count)
        {
            if (byts == null || byts.Length < count || offset >= count) return "";

            var md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(byts, offset, count);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }

        public static string Hash(Stream stream)
        {
            if (stream == null || !stream.CanRead) return "";

            var md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(stream);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
    }
}
